from google.appengine.ext import db
from google.appengine.ext import webapp
from google.appengine.ext.webapp import util
from twitter import Twitter
from database import TwitterUser,FetchHelper
import datetime,re,fetch
import simplejson as json

class Browse(webapp.RequestHandler):

    def get(self):
        self.response.headers['Content-Type'] = "application/json"

        try:    count = int(self.request.get("count"))
        except: count = 20
        if not 0 < count <= 50: count = 20
        
        try:    page = int(self.request.get("page"))
        except: page = 1
        if page < 1: page = 1
        
        json = "["
        query = TwitterUser.all()
        query.order("-text_created_at")
        users = query.fetch(count, count*(page-1))
        
        
        for user in users:
            if not user.text: continue
            text = user.text.replace("\\\"", "'").replace("\"", "'").replace("\r", "").replace("\n", "")
            date = datetime.datetime.strptime(str(user.text_created_at), "%Y-%m-%d %X" )
            date = str(date + datetime.timedelta(hours=8))           
                
            json += "{";
            json += "\"profile_img_url\": \"" + user.profile_image_url + "\",";
            json += "\"screen_name\": \"" + user.screen_name + "\",";
            json += "\"name\": \"" + user.name + "\",";
            json += "\"text\": \"" + text + "\",";
            json += "\"created_at\": \"" + date + "\",";
            json += "\"id\": " + str(user.text_id) + ",";
            json += "\"source\": \"" + user.text_source.replace("\\\"", "'").replace("\"", "'") + "\"";
            json += "},";
        
        json = json[:-1] + "]"
        
        self.response.out.write(json)
        
class Rank(webapp.RequestHandler):

    def get(self):
        self.response.headers['Content-Type'] = "application/json"

        try:    count = int(self.request.get("count"))
        except: count = 20
        if not 0 < count <= 50: count = 20
        
        try:    page = int(self.request.get("page"))
        except: page = 1
        if page < 1: page = 1
                
        json = "["
        query = TwitterUser.all()
        
        if count*(page-1) > 1000:
            offset = int((count*(page-1))/1000)*1000
            tempUser = db.GqlQuery("SELECT * FROM TwitterUser ORDER BY followers_count DESC LIMIT 999,1")
            for i in tempUser: followers_count = i.followers_count
            
            if (offset > 1000):
                offset2 = offset
                while offset2 <> 1000:
                    tempUser = db.GqlQuery("SELECT * FROM TwitterUser WHERE followers_count < :1 ORDER BY followers_count DESC LIMIT 999,1", followers_count)
                    for i in tempUser: followers_count = i.followers_count
                    offset2 -= 1000

            query.filter("followers_count <", followers_count)
            query.order("-followers_count")
            users = query.fetch(count, count*(page-1)-offset)
        else:
            query.order("-followers_count")
            users = query.fetch(count, count*(page-1))
        
        
        for user in users:
            description = user.description and user.description.replace("\\\"", "'").replace("\"", "'").replace("\r", "").replace("\n", "") or ""
            json += "{";
            json += "\"profile_img_url\": \"" + user.profile_image_url + "\",";
            json += "\"screen_name\": \"" + user.screen_name + "\",";
            json += "\"name\": \"" + user.name + "\",";
            json += "\"description\": \"" + description + "\",";
            json += "\"followers_count\": " + str(user.followers_count) + ",";
            json += "\"friends_count\": " + str(user.friends_count) + ",";
            json += "\"statuses_count\": " + str(user.statuses_count);
            json += "},";
        
        json = json[:-1] + "]"
        
        self.response.out.write(json)
        
def main():
  application = webapp.WSGIApplication([('/browse.json', Browse),('/rank.json', Rank)])
  util.run_wsgi_app(application)

if __name__ == '__main__':
  main()
